package com.crm.repository;

import com.crm.entity.Permission;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author 赵祺
 * @date 2020/5/28 16:41
 */
public interface PermissionRepository extends JpaRepository<Permission,Integer>, JpaSpecificationExecutor<Permission> {
    /**
     * 查询是否拥有权限
     */
    @Query(nativeQuery = true,value = "SELECT  DISTINCT(r.role_id),p.* FROM  role_module rm INNER JOIN  module m on m.module_id =  rm.module_id INNER JOIN role r on r.role_id=rm.role_id INNER JOIN user_role ur on ur.role_id  = r.role_id INNER JOIN users u on u.user_id=ur.user_id  INNER JOIN role_permission rp on rp.role_id = r.role_id INNER JOIN permission p on rp.permission_id=p.permission_id where u.user_id=?1")
    List<Permission> getPerMission(String userId);


    /**
     * 通过角色id查询当前角色没有的权限
     * @param id
     * @return
     */
    @Query(value="select * from permission where permission_id not in(select permission_id from role,role_permission where role.role_id=role_permission.role_id and role.role_id=?1 ) ", nativeQuery=true)
    List<Permission> getPermissionByRoleId(Integer id);
    /**
     * 添加角色的权限
     * @param rid
     * @param pid
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "INSERT INTO `crm`.`role_permission` (`role_id`, `permission_id`) VALUES (?1, ?2);  ",nativeQuery = true)
    Integer addRole_Permission(Integer rid,Integer pid);

    /**
     * 删除角色和权限的关系
     * @param rid
     *
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "delete  from role_permission where role_id=?1    ",nativeQuery = true)
    Integer delRole_Permission(Integer rid);


}
